var formatDoc = function (doc) {
    var data = doc.toJSON({ getters: true });
    data.id = doc._id.toString();
    delete data.createdAt;
    delete data.updatedAt;
    delete data.disable;
    delete data._id;
    return data;
};
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};


var Note_Images = function (mongoose, Schema, PorjectName) {
    const ImageSchema = new Schema({
        base64: { type: String, required: true }
    }, { timestamps: true });
    this.module = mongoose.model(PorjectName, ImageSchema, PorjectName);
};



Note_Images.prototype.creat = function (doc, cb) {
    var data = new this.module({ base64: doc });
    // 将单行数据插入到数据库
    data.save(function (err, doc) {
        if (err) {
            cb(err.message, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};
Note_Images.prototype.creatByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var data = [];
    var CreatEvent = () => {
        this.creat(_array[index].data, (error, doc) => {
            if (error) {
                cb(error, null);
            } else {
                var _data = {
                    title: _array[index].title,
                    id: doc.id,
                };
                data.push(_data);
                if (index >= _array.length - 1) {
                    cb(false, data);
                } else {
                    index++;
                    CreatEvent();
                }
            };
        });
    };
    CreatEvent();
};
Note_Images.prototype.delete = function (id, cb) {
    this.module.findByIdAndRemove({ _id: id }, function (err, numRemoved) {
        if (err) {
            cb(err);
        } else {
            cb(false);
        };
    });
};
Note_Images.prototype.deleteByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var deleteEvent = () => {
        this.delete(_array[index], (error) => {
            if (error) {
                cb(error, null);
            } else {
                if (index >= _array.length - 1) {
                    cb(false, []);
                } else {
                    index++;
                    deleteEvent();
                }
            };
        });
    };
    deleteEvent();
};
Note_Images.prototype.get = function (id, cb) {
    this.module.findById(id, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            if (doc) {
                cb(false, formatDoc(doc));
            } else {
                cb('获取图片失败,已经删除');
            };
        };
    });
};


module.exports = Note_Images;